<?php

namespace app\api\controller\plus\activity;

use app\api\controller\Controller;
use app\api\model\order\Cart as CartModel;
use app\api\model\plus\activity\Product as ProductModel;
use app\api\model\plus\activity\Active as ActiveModel;
use app\api\model\plus\coupon\Coupon as CouponModel;
use app\api\model\settings\Setting as SettingModel;
use app\api\model\shop\FullReduce as FullReduceModel;
use app\api\model\user\Favorite as FavoriteModel;
use app\api\model\user\Visit as VisitModel;
use app\common\library\helper;
use app\common\model\supplier\Service as ServiceModel;
use app\common\service\product\BaseProductService;

/**
 * 限时活动产品控制器
 */
class Product extends Controller
{
    /**
     * 限时活动
     */
    public function active($iden)
    {
        $model = new ActiveModel();
        $list = $model->activityList($iden);
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 限时商品
     */
    public function product($activity_id)
    {
        $user = $this->getUser(false);
        $detail = ActiveModel::detailWithTrans($activity_id,$user);

        if ($user != false) {
            $list = (new ProductModel())->getActivityListByUser($activity_id, $user);
        } else {
            $list = (new ProductModel())->getActivityList($activity_id);
        }
        return $this->renderSuccess('', compact('detail', 'list'));
    }

    /**
     * 限时商品详情
     */
    public function detail($activity_product_id)
    {
        $model = new ProductModel();
        $detail = $model->getSeckillDetail($activity_product_id);
        $active = ActiveModel::detailWithTrans($detail['activity_id']);
        $detail['product']['spec_type'] = 20;
        $specData = BaseProductService::getSpecData($detail['product']);
        $skuList = [];
        if(isset($detail['productSku']) && $detail['productSku']) {
            foreach ($detail['productSku'] as $item) {
                $attr = explode('_', $item['productSku']['spec_sku_id']);
                for ($i = 0; $i < count($attr); $i++) {
                    $skuList[$i][] = $attr[$i];
                }
            }
        }
        foreach ($skuList as &$value) {
            $value = array_unique($value);
        }
        //是否显示店铺信息
        $store_open = SettingModel::getStoreOpen();
        return $this->renderSuccess('', compact('detail', 'active', 'specData', 'store_open', 'skuList'));
    }

    /**
     * 限时商品详情，根据普通商品详情修改
     */
    public function detailOne($activity_product_id)
    {
        $params = $this->postData();
        // 限时商品详情
        $actProduct = ProductModel::detail($activity_product_id);
        // 用户信息
        $user = $this->getUser(false);
        // 商品详情
        $model = new \app\api\model\product\Product;
        $product = $model->getDetails($actProduct['product_id'], $this->getUser(false));
        if ($product === false || $product['audit_status'] != 10 || $product['product_status']['value'] != 10) {
            return $this->renderError($model->getError() ?: '商品信息不存在', [], 29);
        }
        // 多规格商品sku信息
        $specData = $product['spec_type'] == 20 ? $model->getManySpecData($product['spec_rel'], $product['sku']) : null;
        $isfollow = 0;
        if ($user) {
            if (FavoriteModel::detail($actProduct['product_id'], 20, $user['user_id'])) {
                $isfollow = 1;
            }
        }
        $product['isfollow'] = $isfollow;
        $dataCoupon['shop_supplier_id'] = $product['shop_supplier_id'];
        $model = new CouponModel;
        $couponList = $model->getWaitList($dataCoupon, $this->getUser(false), 1);
        // 访问记录
        (new VisitModel())->addVisit($user, $product['supplier'], $params['visitcode'], $product);
        // 优惠信息
        $discount = [
            // 商品满减
            'product_reduce' => FullReduceModel::getListByProduct($actProduct['product_id']),
            // 赠送积分
            'give_points' => $this->getGivePoints($product),
            // 商品优惠券
            'product_coupon' => $this->getCouponList($product),
        ];
        //是否显示优惠
        $show_discount = false;
        if (count($discount['product_reduce']) > 0
            || $discount['give_points'] > 0
            || count($discount['product_coupon']) > 0) {
            $show_discount = true;
        }
        //查询限时商品的多规格

        return $this->renderSuccess('', [
            // 商品详情
            'detail' => $product,
            // 优惠信息
            'discount' => $discount,
            // 显示优惠
            'show_discount' => $show_discount,
            // 购物车商品总数量
            'cart_total_num' => $user ? (new CartModel())->getProductNum($user) : 0,
            // 多规格商品sku信息
            'specData' => $specData,
            // 微信公众号分享参数
            'share' => $this->getShareParams('', $product['product_name'], $product['product_name'], '/pages/product/detail/detail', $product['image'][0]['file_path']),
            'couponList' => $couponList,
            //是否显示店铺信息
            'store_open' => SettingModel::getStoreOpen(),
            //是否开启客服
            'service_open' => SettingModel::getSysConfig()['service_open'],
            //店铺客服信息
            'mp_service' => ServiceModel::detail($product['shop_supplier_id']),
        ]);
    }

    /**
     * 赠送积分
     */
    private function getGivePoints($product)
    {
        if ($product['is_points_gift'] == 0) {
            return 0;
        }
        // 积分设置
        $setting = SettingModel::getItem('points');
        // 条件：后台开启开启购物送积分
        if (!$setting['is_shopping_gift']) {
            return 0;
        }
        // 积分赠送比例
        $ratio = $setting['gift_ratio'] / 100;
        // 计算赠送积分数量
        return helper::bcmul($product['product_price'], $ratio, 0);
    }

    /**
     * 获取商品可用优惠券
     */
    private function getCouponList($product)
    {
        // 可领取优惠券
        $model = new CouponModel;
        $user = $this->getUser(false);
        $couponList = $model->getList($user, null, true, $product['shop_supplier_id']);
        $coupon = [];
        foreach ($couponList as $key => $item) {
            if ($item['apply_range'] == 10) {
                $coupon[] = $item;
                // 限制商品
            } else if ($item['apply_range'] == 20) {
                $product_ids = explode(',', $item['product_ids']);
                if (in_array($product['product_id'], $product_ids)) {
                    $coupon[] = $item;
                }
                // 限制分类
            } else if ($item['apply_range'] == 30) {
                $category_ids = helper::getArrayColumn($item["category_list"], "category_id");
                if (in_array($product['category_id'], $category_ids)) {
                    $coupon[] = $item;
                }
            }
        }
        return $coupon;
    }

    /**
     * 获取待审核数量
     */
    public static function getApplyCount()
    {
        return self::where('status', '=', 0)
            ->where('is_delete', '=', 0)
            ->count();
    }

}
